<template>
	<scroll-view class="flex-col page" scroll-y @scroll="onPageScroll">
		<view class="flex-col justify-start relative group">
			<view class="flex-col section" style="margin-bottom: 50rpx">
				<xlm-top-nav :scrollTop="scrollTop" :leftIconColor="'#fff'" :titleColor="'#fff'" :textAlign="'center'"
					title="首页" :showGoBack="false" />
				<view class="flex-col self-stretch">
					<!-- 顶部功能区 -->
					<view class="top-menu">
						<view class="menu-item" v-for="(item, idx) in menuList" :key="idx" @click="toMenu(item)">
							<image :src="item.icon" class="menu-icon" />
							<text class="menu-text">{{ item.text }}</text>
						</view>
					</view>

					<!-- 轮播图 -->
					<view class="banner-wrap">
						<!-- <image src="https://img1.imgtp.com/2023/09/13/4QwQv1Qe.jpg" class="banner-img" /> -->
						<swiper class="banner" :indicator-dots="true" :autoplay="true" :interval="3000"
							:circular="true">
							<swiper-item v-for="(item, index) in swiperList" :key="index">
								<view class="banner-content" @click="handleBannerClick(item)">
									<image v-if="item.thumb" :src="item.thumb" class="image_10"
										style="width: 100%; height: 100%" />
								</view>
							</swiper-item>
						</swiper>
					</view>

					<!-- 赛事筛选tab -->
					<view class="filter-bar">
						<view class="filter-tab" :class="{ active: filterIndex === idx }"
							v-for="(item, idx) in filterTabs" :key="idx" @click="tabClick(item, idx)">
							{{ item.name }}
						</view>
						<view class="filter-sort">
							<text :class="{ active: sortType === 'time' }" @click="sortByTab('time')">按时间</text>
							<text :class="{ active: sortType === 'distance' }" @click="sortByTab('distance')">按距离</text>
						</view>
					</view>

					<!-- 赛事卡片列表 -->
					<view v-for="(item, idx) in eventList" :key="idx" class="event-card"
						@click="toCooperationEventsPage(item)">
						<image :src="item.master_image" class="event-img" />
						<view class="event-status" :class="
                item.status == 'notstart'
                  ? 'status-signup'
                  : item.status == 'signup'
                    ? 'status-signup'
                    : item.status == 'progress'
                      ? 'status-signup'
                      : item.status == 'end'
                        ? 'status-end'
                        : ''
              ">
							<text class="status-dot"></text>
							<text>{{ getEventStatusText(item.status) }}</text>
						</view>
						<view class="event-content">
							<view class="event-title">{{ item.name }}</view>
							<view class="event-info">
								<image :src="imgUrl + 'clock@2x.png'" class="home-icon iconStyle" />
								比赛日期：{{ formatTime(item.competition_time) }}　{{ getEventTypeText(item.type) }}
							</view>
							<view class="event-info">
								<image :src="imgUrl + 'calendar@2x.png'" class="home-icon iconStyle" />
								截止日期：{{ formatTime(item.deadline) }}
							</view>
							<view class="event-info">
								<image :src="imgUrl + 'location3@2x.png'" class="home-icon iconStyle" />
								地址：
								<text style="margin-right: auto">
									{{ item.address }}
								</text>
								<image :src="imgUrl + 'location@2x.png'" class="home-icon iconStyle" />
								<text
									class="distance-text">{{ item.juli ? (item.juli / 1000).toFixed(2) : '0.00' }}km</text>
							</view>
						</view>
					</view>

					<!-- 底部快捷入口 -->
					<view class="footer-bar">
						<!-- <image src="https://img1.imgtp.com/2023/09/13/4QwQv1Qe.jpg" class="footer-logo" /> -->
						<image class="footer-logo" :src="imgUrl + 'WechatIMG136@2x.png'" />
						<view class="footer-menu">
							<template v-for="(item, idx) in footerMenu" :key="idx">
								<!-- 客服使用小程序客服按钮 -->
								<button v-if="item.type === 'customerService'" 
									class="footer-menu-item" 
									open-type="contact" 
									:session-from="sessionFrom"
									bindcontact="onServiceContact">
									<image :src="item.icon" class="footer-menu-icon" />
									<text class="footer-menu-text">{{ item.text }}</text>
								</button>
								<!-- 其他菜单项 -->
								<view v-else class="footer-menu-item" @tap="toFooterMenu(item)">
									<image :src="item.icon" class="footer-menu-icon" />
									<text class="footer-menu-text">{{ item.text }}</text>
								</view>
							</template>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 200rpx"></view>
		<XlmExpressTabbar :current="0" />
	</scroll-view>
</template>
<script setup lang="ts">
	import XlmExpressTabbar from '@/components/XlmExpressTabbar/index.vue'
	import { getEventStatusText, getEventTypeText } from '@/utils/statusUtils.js'
	import { formatTime } from '@/utils/dateUtils.js'
	import XlmTopNav from '@/components/XlmTopNav/index.vue'
	import { ref } from 'vue'
	import { imgUrl } from '@/utils/config'
	import { onShow, onLoad } from '@dcloudio/uni-app'
	import { useRequest } from '@/api'
	const { API_HOME_BANNER_POST, API_NEWS_CUSTOMER_GET, API_HOME_EVENT_POST, API_LOGIN_WX_POST } =
		useRequest()
	const scrollTop = ref(0)
	const onPageScroll = (e) => {
		scrollTop.value = e.detail.scrollTop
	}
	// 页面加载时立即隐藏tabBar
	onLoad(() => {
		// getCodeByWx();//获取code
		// getLocation()//获取位置
	})

	const menuList = [
		{ icon: imgUrl + 'news@2x.png', text: '新闻', type: 'news' },
		{ icon: imgUrl + 'gift@2x.png', text: '活动', type: 'activity' },
		{ icon: imgUrl + 'club@2x.png', text: '俱乐部', type: 'club' },
		{ icon: imgUrl + 'cup@2x.png', text: '赛事合作', type: 'event' },
		{ icon: imgUrl + 'live@2x.png', text: '比赛直播', type: 'live' }
	]

	// const filterTabs = ref(['全部', '田径', '成人'])
	const filterTabs = ref([
		{
			type: 'all',
			name: '全部'
		},
		{
			type: 'athletics',
			name: '田径'
		},
		{
			type: 'adult',
			name: '成人'
		}
	])
	const filterIndex = ref(0)
	const sortType = ref('time')
	const swiperList = ref([
		{ url: imgUrl + 'a.jpg' },
		{ url: imgUrl + 'b.jpg' },
		{ url: imgUrl + 'c.jpg' }
	])
	const eventList = ref([])
	const eventListAll = ref([])
	// 官方视频号信息（可按需配置/从接口获取）
	const officialChannels = ref([
		{
			nickname: '草源田径小将',
			finderUserName: 'sphWvIwcXCi4Xyc' // 可填 sph 开头的视频号ID（可留空）
		}
	])
	const footerMenu = [
		{ icon: imgUrl + 'videoNumber@2x.png', text: '视频号', type: 'videoNumber' },
		{ icon: imgUrl + 'message@2x.png', text: '消息通知', type: 'message' },
		{ icon: imgUrl + 'customerService@2x.png', text: '客服', type: 'customerService' }
	]
	
	// 客服会话来源参数
	const sessionFrom = ref('首页')
	onShow(() => {
		getCodeByWx() //获取code
		getLocation() //获取位置
	})
	const tabClick = (item, idx) => {
		filterIndex.value = idx
		if (item.type === 'all') {
			eventList.value = eventListAll.value
		} else if (item.type === 'athletics') {
			eventList.value = eventListAll.value.filter((item) => item.type === 'athletics')
		} else if (item.type === 'adult') {
			eventList.value = eventListAll.value.filter((item) => item.type === 'adult')
		}
	}
	const sortByTab = (type) => {
		sortType.value = type
		if (sortType.value === 'time') {
			eventList.value = eventList.value.sort((a, b) => a.competition_time - b.competition_time)
		} else if (sortType.value === 'distance') {
			eventList.value = eventList.value.sort((a, b) => a.juli - b.juli)
		}
	}
	const getCodeByWx = async () => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				const code = res.code
				console.log('code', code)
				if (code) {
					doLogin(code)
				}
			},
			fail: (err) => {
				console.error('微信登录失败', err)
				uni.showToast({
					title: '微信登录失败',
					icon: 'none'
				})
			}
		})
	}
	const getLocation = () => {
		wx.getLocation({
			type: 'wgs84',
			success(res) {
				const latitude = res.latitude
				const longitude = res.longitude
				const speed = res.speed
				const accuracy = res.accuracy
				console.log('latitude', latitude)
				console.log('longitude', longitude)
				console.log('speed', speed)
				console.log('accuracy', accuracy)
				getEventList(latitude, longitude) //获取赛事列表
				uni.setStorageSync('latitude', latitude) //缓存经度信息
				uni.setStorageSync('longitude', longitude) //缓存纬度信息
			}
		})
	}
	// 执行登录
	const doLogin = async (code) => {
		const params = {
			code
		}
		try {
			// uni.showLoading({
			//   title: '登录中...'
			// })

			// 调用登录接口
			const res = await API_LOGIN_WX_POST(params)
			console.log('登录接口返回:', res)

			if (res.code === 1) {
				// 登录成功,此时
				uni.setStorageSync('token', res.data.token)
				// uni.setStorageSync('userInfo', res.data.userinfo);

				getBannerList() //获取轮播图
			} else {
				throw new Error(res.msg || '登录失败')
			}
		} catch (error) {
			console.error('登录失败:', error)
			uni.showToast({
				title: error.message || '登录失败，请重试',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const getBannerList = async () => {
		let params = {
			page: 1,
			page_size: 10
		}
		swiperList.value = []
		try {
			const res = await API_HOME_BANNER_POST(params)
			console.log('getBannerList', res)

			if (res.code === 1) {
				if (res.data.data.length > 0) {
					swiperList.value = res.data.data
				} else {
					swiperList.value = []
				}
			} else {
				uni.showToast({ title: res.msg, icon: 'none' })
			}
			console.log('swiperList', swiperList.value)
		} catch (error) {
			uni.showToast({ title: error.message, icon: 'none' })
		}
	}
	const getEventList = async (latitude, longitude) => {
		let params = {
			page: 1,
			page_size: 10,
			lng: longitude,
			lat: latitude
		}
		eventListAll.value = []
		eventList.value = []
		try {
			const res = await API_HOME_EVENT_POST(params)
			console.log('getEventList', res)

			if (res.code === 1) {
				if (res.data.data.length > 0) {
					eventListAll.value = res.data.data
					eventList.value = eventListAll.value //初始化赛事列表
					sortByTab('time') //初始化按时间排序
				} else {
					eventListAll.value = []
				}
			} else {
				uni.showToast({ title: res.msg, icon: 'none' })
			}
			console.log('eventListAll', eventListAll.value)
		} catch (error) {
			uni.showToast({ title: error.message, icon: 'none' })
		}
	}
	const toMenu = (item) => {
		console.log('toMenu', item)
		if (item.type === 'news') {
			// 跳转新闻
			uni.navigateTo({
				url: '/pages/news/index?type=' + item.type,
				fail: (err) => {
					console.error('跳转新闻失败', err)
				}
			})
		} else if (item.type === 'activity') {
			// 跳转活动
			uni.navigateTo({
				url: '/pages/eventActivity/index?type=' + item.type,
				fail: (err) => {
					console.error('跳转活动失败', err)
				}
			})
		} else if (item.type === 'club') {
			// 跳转俱乐部
			uni.navigateTo({
				url: '/pages/clubRanking/index?type=' + item.type,
				fail: (err) => {
					console.error('跳转俱乐部排行失败', err)
				}
			})
		} else if (item.type === 'event') {
			// 跳转赛事合作
			uni.navigateTo({
				url: '/pages/CooperationEvents/index?type=' + item.type,
				fail: (err) => {
					console.error('跳转赛事合作失败', err)
				}
			})
		} else if (item.type === 'live') {
			// // 跳转比赛直播  暂时注释  勿删
			// uni.navigateTo({
			//   url: '/pages/LiveList/index?type=' + item.type,
			//   fail: (err) => {
			//     console.error('跳转比赛直播失败', err)
			//   }
			// })
			// 暂不跳转：弹窗引导复制视频号后去视频号搜索观看
			const info = officialChannels.value?.[0] || { nickname: '视频号', finderUserName: '' }
			promptChannelsManualOpen(info)
		}
	}
	// 提示复制视频号并前往视频号搜索
	const promptChannelsManualOpen = (channelsInfo) => {
		const nickname = channelsInfo?.nickname || '视频号'
		const fid = channelsInfo?.finderUserName || ''
		const tips = `请复制下方信息后，前往 微信 → 发现 → 视频号，搜索并进入观看。\n\n视频号：${nickname}${fid ? `\nID：${fid}` : ''}`

		uni.showActionSheet({
			itemList: fid ? ['复制视频号昵称', '复制视频号ID'] : ['复制视频号昵称'],
			alertText: tips,
			success: (res) => {
				const isCopyName = res.tapIndex === 0
				const copyText = isCopyName ? nickname : fid
				if (!copyText) return
				uni.setClipboardData({
					data: copyText,
					success: () => {
						const what = isCopyName ? '视频号昵称' : '视频号ID'
						uni.showModal({
							title: '复制成功',
							content: `已复制${what}\n请前往“微信-发现-视频号”搜索查看`,
							showCancel: false,
							confirmText: '我知道了'
						})
						// const tip = `已复制${what}\n请前往“微信-发现-视频号”搜索查看`
						// uni.showToast({ title: tip, icon: 'none', duration: 3000 })
					}
				})
			}
		})
	}
	const toFooterMenu = (item) => {
		console.log('toFooterMenu', item)
		if (item.type === 'videoNumber') {
			wx.openChannelsUserProfile({
				finderUserName: "sphHYscTmjthMWQ",
			});
		} else if (item.type === 'message') {
			uni.navigateTo({
				url: '/pages/message/index'
			})
		} else if (item.type === 'customerService') {
			// 客服按钮已在模板中处理，这里保留注释
			// getNewsCustomer()
		}
	}
	
	// 客服会话回调
	const onServiceContact = (e) => {
		console.log('打开客服会话', e)
		console.log('会话来源:', sessionFrom.value)
		
		// 可以在这里获取客服会话信息
		// e.detail 包含客服会话相关信息
	}
	// 判断是否为外部链接
	const isExternalLink = (url) => {
		if (!url) return false

		// 包含协议的外部链接
		if (url.startsWith('http://') || url.startsWith('https://')) {
			return true
		}

		// 包含常见域名的外部链接
		if (
			url.includes('.com') ||
			url.includes('.cn') ||
			url.includes('.net') ||
			url.includes('.org') ||
			url.includes('.edu') ||
			url.includes('.gov')
		) {
			return true
		}

		// 包含IP地址的外部链接
		if (url.match(/^\d+\.\d+\.\d+\.\d+/) || url.includes('localhost')) {
			return true
		}

		return false
	}

	// 处理轮播图点击
	const handleBannerClick = (item) => {
		console.log('轮播图点击', item)

		if (!item) {
			uni.showToast({
				title: '无效的轮播图数据',
				icon: 'none'
			})
			return
		}

		// 获取链接URL，支持多种字段名
		let targetUrl = item.url || item.link_url || item.link || item.href || ''
		let targetTitle = item.title || item.bannername || '详情'
		console.log('targetUrl', targetUrl)
		console.log('targetTitle', targetTitle)

		if (!targetUrl || targetUrl.trim() === '') {
			uni.showToast({
				title: '暂无链接',
				icon: 'none'
			})
			return
		}

		// 如果是外部链接但没有协议，自动添加https://
		if (
			isExternalLink(targetUrl) &&
			!targetUrl.startsWith('http://') &&
			!targetUrl.startsWith('https://')
		) {
			targetUrl = 'https://' + targetUrl
			console.log('自动添加协议后的URL:', targetUrl)
		}

		// 处理外部链接
		if (isExternalLink(targetUrl)) {
			try {
				uni.navigateTo({
					url: `/pages/webview/index?url=${encodeURIComponent(targetUrl)}&title=${encodeURIComponent(targetTitle)}`,
					fail: (err) => {
						console.error('跳转webview失败', err)
						// 如果webview跳转失败，尝试使用系统浏览器打开
						uni.showModal({
							title: '提示',
							content: '是否使用系统浏览器打开链接？',
							success: (res) => {
								if (res.confirm) {
									// #ifdef APP-PLUS
									plus.runtime.openURL(targetUrl)
									// #endif
									// #ifdef H5
									window.open(targetUrl, '_blank')
									// #endif
									// #ifdef MP-WEIXIN
									uni.showToast({
										title: '请复制链接到浏览器打开',
										icon: 'none'
									})
									// #endif
								}
							}
						})
					}
				})
			} catch (error) {
				console.error('处理外部链接失败', error)
				uni.showToast({
					title: '链接处理失败',
					icon: 'none'
				})
			}
		} else {
			// 处理内部页面跳转
			try {
				// 确保内部链接以/开头
				if (!targetUrl.startsWith('/')) {
					targetUrl = '/' + targetUrl
				}

				uni.navigateTo({
					url: targetUrl,
					fail: (err) => {
						console.error('内部页面跳转失败', err)
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						})
					}
				})
			} catch (error) {
				console.error('处理内部链接失败', error)
				uni.showToast({
					title: '页面跳转失败',
					icon: 'none'
				})
			}
		}
	}

	const getNewsCustomer = async () => {
		console.log('getNewsCustomer+++++')
		try {
			const res = await API_NEWS_CUSTOMER_GET()
			console.log('getNewsCustomer————————————', res)

			if (res.code === 1) {
				// newsDetail.value = res.data;
				// // 拨打电话
				// uni.makePhoneCall({
				//   phoneNumber: '4000692928'
				// });
				// 拨打电话
				uni.makePhoneCall({
					phoneNumber: res.data.customer
				})
			} else {
				uni.showToast({ title: res.msg, icon: 'none' })
			}
		} catch (error) {
			console.log('error>>>>>>>+++++', error)
			uni.showToast({ title: error.response?.data.msg, icon: 'none' })
		}
	}
	//跳转赛事详情
	const toCooperationEventsPage = (item) => {
		console.log('toCooperationEventsPage', item)
		uni.navigateTo({
			url: '/pages/event/eventDetails/index?id=' + item.id
		})
	}
</script>
<style lang="scss" scoped>
	@import './index.scss';
</style>